package com.jaws.demo.controller;

import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Member;
import com.ecwid.consul.v1.agent.model.Service;
import com.ecwid.consul.v1.health.model.Check;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * consul操作
 *
 * @author liangqm
 * @date 2018-04-16 9:42:18
 * @since v1.0.0
 */
@RestController
public class ConsulApiController {
	private static Logger log = LoggerFactory.getLogger(ConsulApiController.class);

	@Resource
	private ConsulClient consulClient;

	/**
	 * 获取所有服务
	 *
	 * @return
	 * @author liangqm
	 * @date 2018-04-16 9:41:18
	 * @since v1.0.0
	 */
	@ApiOperation(value = "剔除所有无效的服务实例", notes = "剔除所有无效的服务实例")
	@RequestMapping(value = "/consul/allservicer", method = RequestMethod.GET)
	void getAllServers() {
		log.info("***********************consul上无效服务清理开始*******************************************");

		//获取所有的members的信息
		List<Member> members = consulClient.getAgentMembers().getValue();

		for (int i = 0; i < members.size(); i++) {
			//获取每个member的IP地址
			String address = members.get(i).getAddress();
			//根据role变量获取每个member的角色  role：consul---代表服务端   role：node---代表客户端
			String role = members.get(i).getTags().get("role");
			log.info("member node==> {}; member node role =>{} ", address, role);

			//判断是否为client
			if (role.equals("node")) {
				//将IP地址传给ConsulClient的构造方法，获取对象
				ConsulClient clearClient = new ConsulClient(address);

				//获取 member node下 所有的 service name
				Set<String> serviceNames = Sets.newConcurrentHashSet();

				//获取 member node 下所有服务，返回结果map key=serviceId ,value=Service
				Map<String, Service> servicesMap = clearClient.getAgentServices().getValue();
				Iterator<Map.Entry<String, Service>> iterator = servicesMap.entrySet().iterator();
				while (iterator.hasNext()) {
					Map.Entry<String, Service> serviceMap = iterator.next();
					serviceNames.add(serviceMap.getValue().getService());
				}

				log.info("member node==> {}; member node role =>{}; serviceNames==> {} ", address, role, serviceNames);

				for (String serviceName : serviceNames) {
					Response<List<Check>> checkList = consulClient.getHealthChecksForService(serviceName, null);
					List<Check> checks = checkList.getValue();
					for (Check check : checks) {
						log.info("member node==> {}; check==> {}",address,check);
						Check.CheckStatus checkStatus = check.getStatus();
						if (checkStatus != Check.CheckStatus.PASSING) {
							String checkServiceId = check.getCheckId().substring(new String("service:").length());
							log.info("member node==> {}; serviceId==>{}; serviceName==>{} ，准备清理...................", address, checkServiceId, serviceName);
							clearClient.agentServiceDeregister(checkServiceId);
						}
					}

				}
			}
		}
	}
}